package service

import (
	"flag"
	"fmt"
	"gitee.com/zxs-micro/zxs-micro-common/grpc"
	"gitee.com/zxs-micro/zxs-micro-common/log"
	"gitee.com/zxs-micro/zxs-micro-fuwufaxian/grpc/fwfxserver"
	"gitee.com/zxs-micro/zxs-micro-fuwufaxian/grpc/protos/fwfx"
	"github.com/spf13/viper"
	"net"
	"os"
	"os/signal"
	"strings"
	"sync"
	"syscall"
	"time"
)

type Fuwufaxian struct {
	fwLock sync.Mutex
	sigs   chan os.Signal
	fwfxs  *fwfxserver.FwfxService
}

var (
	fConfig     = flag.String("config", "cccfff.yaml", "configuration file to load")
	fConfigPath = flag.String("config-path", "fuwufaxian/config", "directory containing additional *.yaml files")
)

func (s *Fuwufaxian) Start() {
	flag.Parse()
	viper.AddConfigPath(*fConfigPath)
	viper.AddConfigPath(".")
	viper.AddConfigPath("config")
	*fConfig = strings.Replace(*fConfig, ".yaml", "", 1)
	viper.SetConfigName(*fConfig)
	err := viper.ReadInConfig()
	log.Init(viper.GetString("log.level"), viper.GetString("log.format"))
	if err != nil {
		log.Log.Errorf("获取系统配置失败：%s", err.Error())
		panic("can not read config: " + err.Error())
	}

	conf := GetFwfxGrpcConfig()
	selfport := viper.GetString("server.port")
	addr := ":" + selfport

	ctx, err := net.Listen("tcp", addr)
	if err != nil {
		log.Log.Errorf("创建grpc服务失败：%s", err.Error())
		panic(err)
		return
	}

	grpcserver, err := grpc.NewGrpcServer(ctx, conf)
	if err != nil {
		log.Log.Errorf("创建grpc服务失败：%s", err.Error())
		panic(err)
		return
	}

	s.fwfxs = fwfxserver.NewFwfxService()
	s.fwfxs.ServerType = viper.GetString("server.type")
	s.fwfxs.LocalIp = viper.GetString("server.faxian.localip")
	s.fwfxs.LocalPort = viper.GetString("server.port")
	fwfx.RegisterFuwufaxiansServer(grpcserver.Server(), s.fwfxs)

	var servErr = make(chan error)
	go func() {
		err := grpcserver.Start()
		if err != nil {
			log.Log.Errorf("启动服务发现时出现错误：%s", err.Error())
		}
		servErr <- err
	}()

	go func() {
		//向自己注册自己
		<-time.After(time.Second)
		log.Log.Info("向自己注册自己！")
		var sid = ""
		fx, err := fwfxserver.GenerateFwfxClients("127.0.0.1:" + selfport)
		if err == nil {
			sid, err = fx.InjectNewServer("127.0.0.1:"+selfport, "", s.fwfxs.ServerType)
			//fmt.Println(err)
			if err == nil {
				s.fwfxs.SelfId = sid
				log.Log.Info("向自己注册自己成功！自己的ID是：", sid)
			} else {
				servErr <- err
			}
		} else {
			servErr <- err
		}

	}()

	log.Log.Infof("服务发现已启动！")
	s.sigs = make(chan os.Signal, 1)
	signal.Notify(s.sigs, syscall.SIGINT, syscall.SIGTERM)
	select {
	case <-s.sigs:
		log.Log.Info("服务发现关闭.....")
	case shuterr := <-servErr:
		log.Log.Error(shuterr)
		log.Log.Error("由于出现错误，服务发现关闭......")
	}
	os.Exit(0)
}

func (s *Fuwufaxian) Shutdown(f bool) {
	signal.Stop(s.sigs)
	fmt.Println("服务发现关闭.....")
	os.Exit(0)
}
